// 防抖函数
export function debounce(func: Function, wait: number = 250) {
    let timeout: NodeJS.Timeout;
    return function executedFunction(...args: any[]) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 节流函数
export function throttle(func: Function, wait: number = 250) {
    let inThrottle: boolean;
    return function executedFunction(...args: any[]) {
        if (!inThrottle) {
            func(...args);
            inThrottle = true;
            setTimeout(() => (inThrottle = false), wait);
        }
    };
}

// 两个版本号比较
export function compareVersion(version1: string, version2: string) {
    let v1 = version1.split('.')
    let v2 = version2.split('.')
    const len = Math.max(v1.length, v2.length)

    while (v1.length < len) {
        v1.push('0')
    }
    while (v2.length < len) {
        v2.push('0')
    }

    for (let i = 0; i < len; i++) {
        const num1 = parseInt(v1[i])
        const num2 = parseInt(v2[i])

        if (num1 > num2) {
            return 1
        } else if (num1 < num2) {
            return -1
        }
    }

    return 0
}

// 随机范围内的数字
export function randomNumber(max: number, min: number = 0) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

// 是否为负数
export function hasMinus(v: string | number) {
    if (typeof v === 'number') return v < 0;
    return parseFloat(v) < 0;
}
